/**
 * 多队伍计分功能实现
 * 处理队伍的添加、删除和分数更新
 */
 document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const teamsContainer = document.getElementById('teamsContainer');
    const addTeamBtn = document.getElementById('addTeamBtn');
    const submitBtn = document.getElementById('submitBtn');
    let teams = [];
    // 移除teamIdCounter变量，使用后端返回的ID
    
    /**
     * 初始化队伍数据
     */
    function initTeams() {
        // 从后端API加载队伍数据
        fetch('/api/teams')
            .then(response => {
                if (!response.ok) {
                    throw new Error('无法加载队伍数据');
                }
                return response.json();
            })
            .then(data => {
                teams = data;
                renderTeams();
            })
            .catch(error => {
                console.error('初始化队伍数据时出错:', error);
                alert('加载队伍数据失败，请刷新页面重试！');
            });
    }

    /**
     * 添加新队伍
     */
    function addTeam() {
        const teamName = prompt('请输入队名:', '');
        if (!teamName) return;
        let scoreStr = prompt('请输入初始分数（默认为0）:', '0');
        if (scoreStr === null) return;
        let score = parseInt(scoreStr, 10);
        if (isNaN(score) || score < 0) score = 0;
        if (teams.length >= 100) {
            alert('最多只能添加100个队伍');
            return;
        }
        // 发送请求到后端创建队伍
        fetch('/api/add-team', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ name: teamName, score: score })
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('创建队伍失败');
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                const newTeam = {
                    id: data.id, // 使用后端返回的ID
                    name: data.name,
                    score: data.score
                };
                teams.push(newTeam);
                renderTeams();
                alert('添加队伍成功！');
            } else {
                alert('添加队伍失败：' + (data.error || '未知错误'));
            }
        })
        .catch(error => {
            console.error('添加队伍时出错:', error);
            alert('添加队伍失败，请重试！');
        });
    }

    /**
     * 删除队伍
     * @param {number} teamId - 要删除的队伍ID
     */
    function removeTeam(teamId) {
        // 发送删除请求到后端
        fetch(`/api/teams/${teamId}`, {
            method: 'DELETE'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('删除队伍失败');
            }
            return response.json();
        })
        .then(data => {
            teams = teams.filter(team => team.id !== teamId);
            renderTeams();
        })
        .catch(error => {
            console.error('删除队伍时出错:', error);
            alert('删除队伍失败，请重试！');
        });
    }

    /**
     * 更新队伍分数（本地暂存，不立即提交到服务器）
     * @param {number} teamId - 队伍ID
     * @param {number} points - 分数变化值（正数为加分，负数为减分）
     */
    function updateTeamScore(teamId, points) {
        const team = teams.find(team => team.id === teamId);
        if (team) {
            const newScore = Math.max(0, team.score + points);
            team.score = newScore; // 仅更新本地分数
            renderTeams(); // 刷新显示
        }
    }

    /**
     * 渲染所有队伍
     */
    function renderTeams() {
        // 清空容器
        teamsContainer.innerHTML = '';
    
        // 渲染每个队伍
        teams.forEach(team => {
            const teamCard = document.createElement('div');
            teamCard.className = 'team-card';
            teamCard.dataset.teamId = team.id;
            teamCard.innerHTML = `
                <div class="team-header">
                    <h2>${team.name}</h2>
                    <button class="remove-team-btn">×</button>
                </div>
                <div class="team-score">${team.score}</div>
                <div class="team-buttons">
                    <button class="btn decrease-btn">- 减分</button>
                    <button class="btn increase-btn">+ 加分</button>
                </div>
            `;
    
            // 添加事件监听器
            teamCard.querySelector('.remove-team-btn').addEventListener('click', () => {
                removeTeam(team.id);
            });
    
            teamCard.querySelector('.decrease-btn').addEventListener('click', () => {
                updateTeamScore(team.id, -1);
            });
    
            teamCard.querySelector('.increase-btn').addEventListener('click', () => {
                updateTeamScore(team.id, 1);
            });
    
            teamsContainer.appendChild(teamCard);
        });
    }

    /**
     * 提交所有队伍分数
     */
    function submitAllScores() {
        // 发送分数数据到后端API
        fetch('/api/update-scores', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(teams)
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(data => {
            const submissionTime = new Date().toLocaleString();
            let scoresText = teams.map(team => `${team.name}: ${team.score}`).join('\n');
            alert(`所有分数提交成功！\n\n${scoresText}\n\n提交时间: ${submissionTime}`);
            console.log('分数提交数据:', data);
        })
        .catch(error => {
            console.error('提交分数时出错:', error);
            alert('提交失败，请重试！');
        });
    }

    // 绑定事件监听器
    addTeamBtn.addEventListener('click', addTeam);
    submitBtn.addEventListener('click', submitAllScores);

    // 初始化队伍
    initTeams();
});